﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Blog.Model;
using Blog.IService;
using Blog.ServiceContainer;
using Blog.Util;
using System.Net.Mail;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System.IO;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
using System.Collections;
using System.Data;
using Dapper;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using WebApi.Model;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authorization;

namespace WebApi.Controllers
{
    //[EnableCors("CorsPolicy")]//跨域
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        #region 头部
        public static string conStr = "server=.;uid=sa;pwd=123456;database=Helper";
        HttpClient client = new HttpClient();
        private DistributedCache _Cache;
        private JwtSettings _jwtSettings;
        JWtToken jwttoken = new JWtToken();
        private HttpResponseMessage WriteMsg(string Msg)
        {
            return new HttpResponseMessage { Content = new StringContent(Msg, System.Text.Encoding.UTF8, "application/json") };
        }
        /// <summary>
        ///   构造注入
        /// </summary>
        /// <param name="Cache"></param>
        public ValuesController(IDistributedCache Cache, IOptions<JwtSettings> _jwtSettingsAccesser)
        {
            _Cache = new DistributedCache(Cache);
            _jwtSettings = _jwtSettingsAccesser.Value;
        }
        #endregion

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            _Cache.Remove("Aativity");
            using (var db = new SqlConnection(conStr))
            {
                //最近的活动
                List<Aativity> list = new List<Aativity>();
                list = db.Query<Aativity>("p_Aativity",
                                         null,
                                         null,
                                         true,
                                          null,
                                          CommandType.StoredProcedure).ToList();
                DateTime NowDate = DateTime.Now;
                foreach (var item in list)
                {
                    double day = 0;
                    DateTime dateTime = DateTime.Parse(item.Date);
                    day = (NowDate - dateTime).TotalDays;
                    int num = Convert.ToInt32(day);
                    if (num == 0)
                    {
                        num = Convert.ToInt32(day * 24);
                        if (num == 0)
                        {
                            num = Convert.ToInt32(day * 24 * 24);
                            if (num != 0)
                            {
                                num = Convert.ToInt32(day * 24 * 24 * 24);
                                item.Date = "文章创建于" + num.ToString() + "秒前";
                            }
                            else
                                item.Date = "文章创建于" + num.ToString() + "分钟前";
                        }
                        else
                        {
                            item.Date = "文章创建于" + num.ToString() + "小时前";
                        }
                    }
                    if (num < 30 && num != 0)
                    {
                        item.Date = "文章创建于" + num.ToString() + "天前";
                    }
                    if (num >= 30 && num < 365)
                    {
                        num = num / 30;
                        item.Date = "文章创建于" + num.ToString() + "月前";
                    }
                    if (num >= 365)
                    {
                        num = num / 365;
                        item.Date = "文章创建于" + num.ToString() + "年前";
                    }
                }
                _Cache.Add("Aativity", JsonConvert.SerializeObject(list));
            }

            return new string[] { "Node1", "value2" };
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [Route("UpfileImage")]
        public JsonResult UpfileImage()
        {
            var file = Request.Form.Files[0];
            var filename = Guid.NewGuid().ToString();
            var sub = file.FileName.Substring(file.FileName.LastIndexOf('.'));
            filename += sub;
            var new_path = Path.Combine("images/", file.FileName);
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", new_path);
            using (FileStream fs = System.IO.File.Create(path))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            Hashtable has = new Hashtable();
            has.Add("data", "http://192.168.137.1:5001//" + new_path);

            JsonResult json = new JsonResult(has);
            return json;
        }

        #region 登录注册
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [Route("Register")]
        [HttpPost]
        public JsonResult Register(UserInfo userInfo)
        {
            IUserInfoService us = Container.Resolve<IUserInfoService>();
            UserInfo userInfo1 = us.GetModel(a => a.Uname == userInfo.Uname).FirstOrDefault();
            //MailAddress MessageFrom = new MailAddress("wufan19980120@163.com"); //发件人邮箱地址
            //string MessageTo = userInfo.Email; //收件人邮箱地址
            //string MessageSubject = "您的用户名和密码"; //邮件主题
            //string MessageBody = "用户名：" + userInfo.Uname + "，密码：" + userInfo.Upwd;
            //if (EmailRegister.Send(MessageFrom, MessageTo, MessageSubject, MessageBody))
            //{
            try
            {
                if (userInfo1 == null)
                {
                    us.Add(userInfo);
                    _Cache.Remove("User");
                    _Cache.Add("User", JsonConvert.SerializeObject(us.GetModel(a => true).ToList()));
                    return new JsonResult("注册成功,用户名和密码已发至您的邮箱！");
                }
                else
                    return new JsonResult("该用户名已存在！");
            }
            catch (Exception ex)
            {
                return new JsonResult("注册失败！");
            }
            //}
            //else
            //{
            //    return new JsonResult("注册失败！原因：邮箱不正确！");
            //}
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [Route("Login")]
        [HttpPost]
        public ActionResult Login([FromBody]UserInfo user)
        {
            string strResult = "";
            IUserInfoService userInfoService = Container.Resolve<IUserInfoService>();
            UserInfo userInfo = new UserInfo();
            userInfo = userInfoService.GetModel(a => a.Email == user.Email && a.Upwd == user.Upwd).FirstOrDefault();
            //判断用户是否存在
            if (userInfo != null)
            {
                //用户唯一 返回口令
                jwttoken.Token = MakeToken(userInfo);
                jwttoken.Success = true;
            }
            strResult = JsonConvert.SerializeObject(jwttoken);
            return Content(strResult);
        }
        [Authorize]
        [Route("CheckLogin")]
        public string CheckLogin()
        {
            return "";
        }
        /// <summary>
        /// MakeToken
        /// </summary>
        /// <param name="item">用户Model</param>
        /// <returns>Token</returns>
        private string MakeToken(UserInfo item)
        {
            string strToken = "";
            var claim = new Claim[]{
            new Claim(ClaimTypes.Name,item.Uname),
           // new Claim(ClaimTypes.Role,item.RoleID),
            new Claim("UserID",item.Userid.ToString())
            };
            //对称秘钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            //签名证书(秘钥，加密算法)
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            //生成token [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包，并引用System.IdentityModel.Tokens.Jwt命名空间
            var token = new JwtSecurityToken
            (
            issuer: _jwtSettings.Issuer,

            audience: _jwtSettings.Audience,

            claims: claim,

            notBefore: DateTime.Now,

            expires: DateTime.Now.AddHours(6),//过期时间

            signingCredentials: creds
            );
            try
            {
                //生成口令
                strToken = new JwtSecurityTokenHandler().WriteToken(token);
            }
            catch
            {
            }
            return strToken;
        }
        #endregion

        #region 填充页面
        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns>
        [Route("ceshi")]
        //[HttpPost]
        public JsonResult ceshi()
        {
            IAttentService attentService = Container.Resolve<IAttentService>();
            Attent attent = attentService.GetModel(a => a.CategoryId == 1).FirstOrDefault();
            attentService.Delete(attent);
            return new JsonResult("");
        }

        #region 主页
        /// <summary>
        ///  填充主页主模块
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [Route("Parent")]
        public JsonResult Parent()
        {
            var Cache = JsonConvert.DeserializeObject<List<Parent>>(_Cache.Get("zmk").ToString());
            JsonResult json = new JsonResult(Cache);
            return json;
        }
        /// <summary>
        /// 被推荐的文章
        /// </summary>
        /// <returns></returns>
        [Route("GetCommArticle")]
        public JsonResult GetCommArticle()
        {
            try
            {
                List<Article> article = new List<Article>();
                article = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString());//.ToList();
                List<Article> list = article
                    .Where(a => a.Recommend.Trim() == "on")
                    .ToList();
                //.Select(a => new { Articleid = a.Articleid, Title = a.Title, Categoryid = a.CategoryId }).ToList();
                JsonResult json = new JsonResult(list);
                return json;
            }
            catch (Exception ex)
            {
                List<Article> list = new List<Article>();
                JsonResult json = new JsonResult(list);
                return json;
            }

        }
        /// <summary>
        /// 最近的活动
        /// </summary>
        /// <param name="num">返回的行数</param>
        /// <returns></returns>
        [Route("LatelyAativity")]
        public JsonResult LatelyAativity(int num)
        {
            List<Aativity> list = new List<Aativity>();
            list = JsonConvert.DeserializeObject<List<Aativity>>(_Cache.Get("Aativity").ToString())
            .Take(num).ToList();
            return new JsonResult(list);
        }
        #endregion

        #region 栏目
        /// <summary>
        /// 根据主模块编号填充栏目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("Category")]
        public JsonResult Category(string id)
        {
            int no = int.Parse(id);
            List<Model.Category_List> list = new List<Model.Category_List>();
            List<Category> cate = JsonConvert.DeserializeObject<List<Category>>(_Cache.Get("lm").ToString()).Where(a => a.Parentid == no).ToList();
            foreach (var item in cate)
            {
                Model.Category_List category_List = new Model.Category_List();
                List<Article> article = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString())
                    .OrderByDescending(a => a.Recommend)
                    .Where(a => a.CategoryId == item.CategoryId)
                    .Take(5)
                    .ToList();
                category_List.category = item;
                category_List.articles = article;
                category_List.ArticleCount = article.Count;
                list.Add(category_List);
            }
            JsonResult json = new JsonResult(list);
            return json;
        }
        /// <summary>
        /// 获取文章列表
        /// </summary>
        /// <param name="id">栏目编号</param>
        /// <returns></returns>
        [Route("ArticleList")]
        public JsonResult ArticleList(int id)
        {
            List<Article> article = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString())
                .Where(a => a.CategoryId == id)
                .OrderByDescending(a => a.Recommend)
                .ToList();

            return new JsonResult(article);
        }
        #endregion

        #region 文章
        /// <summary>
        /// 获取文章导航
        /// </summary>
        /// <returns></returns>
        [Route("ArticleNav")]
        public JsonResult ArticleNav(int id)
        {
            List<Article> article = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString())
                   .Where(a => a.CategoryId == id)
                   .OrderByDescending(a => a.Recommend).ToList();
            int count = article.Count;
            article = article.Take(10).ToList();
            return new JsonResult(new { list = article, count = count });
        }
        /// <summary>
        /// 根据文章编号获取文章内容
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("Article")]
        public JsonResult Article(int id)
        {
            //文章信息
            Article article = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString()).Where(a => a.Articleid == id).FirstOrDefault();
            //最近信息
            Aativity aativity = JsonConvert.DeserializeObject<List<Aativity>>(_Cache.Get("Aativity").ToString()).Where(a => a.Articleid == id).FirstOrDefault();
            //管理员信息
            Admin admin = JsonConvert.DeserializeObject<List<Admin>>(_Cache.Get("admin").ToString()).Where(a => a.Adminid == article.Adminid).FirstOrDefault();
            string info = "";
            foreach (var item in strUitl.datestr)
            {
                if (aativity.Date.Contains(item))
                {
                    Regex r = new Regex(@"\d");//正则
                    Match m = r.Match(aativity.Date);//匹配
                    info = m.Value.ToString() + item + "前" + "·更新于";
                    break;
                }
            }
            //id-文章编号、title-文章标题、day-更新天数、adminname-管理员名称
            JsonResult json = new JsonResult(new { id = article.Articleid, title = article.Title, day = info, AdmiNname = admin.AdminName, Content = article.Content });
            return json;
        }
        /// <summary>
        /// 这篇文章有帮助吗
        /// </summary>
        /// <param name="id">文章编号</param>
        ///<param name="result">点击的按钮是否为有帮助</param>
        /// <returns>总人数和有帮助的人数</returns>
        [Route("HeplerNum")]
        public JsonResult HeplerNum(int id, bool result)
        {
            IArticleService articleService = Container.Resolve<IArticleService>();
            Article article = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString())
                .Where(a => a.Articleid == id).FirstOrDefault();
                if (result)
                    article.HelperNum += 1;
                else
                    article.NoHelperNum += 1;
                articleService.Update(article);
            int Total = (article.HelperNum + article.NoHelperNum);
            _Cache.Remove("wz");
            _Cache.Add("wz", JsonConvert.SerializeObject(articleService.GetModel(a => true).ToList()));
            return new JsonResult(new { TotalNum = Total, HelperNum = article.HelperNum });
        }
        /// <summary>
        /// 初始化有帮助的人数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("TotalNum")]
        public JsonResult TotalNum(int id)
        {
            try
            {
                Article article = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString())
             .Where(a => a.Articleid == id).FirstOrDefault();
                int Total = (article.HelperNum + article.NoHelperNum);
                return new JsonResult(new { TotalNum = Total, HelperNum = article.HelperNum });
            }
            catch (Exception)
            {
                return new JsonResult(new { TotalNum = 0, HelperNum = 0 });
            }

        }
        /// <summary>
        /// 相关文章
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        [Route("ReleArticle")]
        public JsonResult ReleArticle(int id)
        {
            List<Article> articles = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString());
            string key = articles.Where(a => a.Articleid == id).FirstOrDefault().Keyword;
            try
            {
                string[] str = key.Split('、');
                foreach (var item in str)
                {
                    if (articles.Count > 5)
                        articles = articles.Where(a => a.Keyword.Contains(item)).ToList();
                    else
                        break;
                }
            }
            catch (Exception)
            {
                string str = key;
                articles = articles.Where(a => a.Keyword.Contains(str)).ToList();
            }
            return new JsonResult(articles.Take(5).ToList());
        }
        #endregion

        #region 搜索
        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="content">搜索的内容</param>
        /// <returns></returns>
        [Route("search")]
        public JsonResult Search(int page, string content)
        {
            List<Model.Search> searches = new List<Model.Search>();
            List<Article> articles = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString()).ToList();
            foreach (var item in articles)
            {
                Model.Search search = new Model.Search();
                search.ArticleId = item.Articleid;
                search.ArticleName = item.Title;
                search.CategoryId = item.CategoryId;
                try
                {
                    search.Thumbs = item.HelperNum;
                }
                catch (Exception)
                {
                    search.Thumbs = 0;
                }

                string[] strs = item.Content.Split('。');
                //匹配内容
                string Scontent = "";
                if (item.Title.Contains(content))
                {
                    foreach (var str in strs)
                    {
                        if (str.Contains(content))
                        {
                            Scontent += str;
                        }
                    }
                    if (Scontent == "") { Scontent = strs[0]; }
                    search.Content = Scontent;
                    searches.Add(search);
                }
                else
                {
                    foreach (var str in strs)
                    {
                        if (str.Contains(content))
                        {
                            Scontent += str;
                        }
                    }
                    if (Scontent != "")
                    {
                        search.Content = Scontent;
                        searches.Add(search);
                    }
                }
            }
            List<Aativity> aativities = JsonConvert.DeserializeObject<List<Aativity>>(_Cache.Get("Aativity").ToString())
                .ToList();
            foreach (var item in strUitl.datestr)
            {
                foreach (var item1 in aativities)
                {
                    if (item1.Date.Contains(item))
                    {
                        Regex r = new Regex(@"\d");//正则
                        Match m = r.Match(item1.Date);//匹配
                        item1.Date = m.Value.ToString() + item + "前" + "·更新于";
                        break;
                    }
                }
            }
            foreach (var item in searches)
            {
                foreach (var item1 in aativities)
                {
                    if (item.ArticleId == item1.Articleid)
                    {
                        item.Day = item1.Date;
                        item.CategoryName = item1.Cname;
                    }
                }
            }
            List<Parent> parents = JsonConvert.DeserializeObject<List<Parent>>(_Cache.Get("zmk").ToString());
            List<Category> categories = JsonConvert.DeserializeObject<List<Category>>(_Cache.Get("lm").ToString());
            foreach (var item in searches)
            {
                foreach (var item1 in categories)
                {
                    if (item.CategoryId == item1.CategoryId)
                    {
                        item.ParentId = item1.Parentid.Value;
                        string name = parents.Where(a => a.Parentid == item.ParentId).FirstOrDefault().Pname;
                        item.ParentName = name;
                    }
                }
            }
            return new JsonResult(new { total = searches.Count, row = searches.Skip(10 * (page - 1)).Take(10).ToList() });
        }
        #endregion

        #region 工单
        /// <summary>
        /// 问题分类
        /// </summary>
        /// <returns></returns>
        [Route("WorkCategory")]
        public JsonResult WorkCategory()
        {
            IProblemService problemService = Container.Resolve<IProblemService>();
            List<Problem> problems = problemService.GetModel(a => a.PPno==0).ToList();
            return new JsonResult(problems);
        }
        [Route("GetWorkChidren")]
        public JsonResult GetWorkChidren(string id) {
            int no = int.Parse(id);
            IProblemService problemService = Container.Resolve<IProblemService>();
            List<Problem> problems = problemService.GetModel(a =>a.PPno== no).ToList();
            return new JsonResult(problems);
        }
        /// <summary>
        /// 工单提交
        /// </summary>
        /// <param name="workOrder"></param>
        /// <returns></returns>
        [Route("WorkOrder")]
        public JsonResult WorkOrder([FromBody]WorkOrder workOrder)
        {
            IWorkOrderService workOrderService = Container.Resolve<IWorkOrderService>();
            try
            {
                workOrderService.Add(workOrder);
                return new JsonResult(Message.Success_Add);
            }
            catch (Exception)
            {
                return new JsonResult(Message.Error_Add);
            }
        }
        #endregion

        #region 评论
        [Route("AddComment")]
        [Authorize]
        [HttpPost]
        public JsonResult AddComment([FromBody]Comment comment)
        {
            ICommentService commentService = Container.Resolve<ICommentService>();
            try
            {
                comment.CommDate = DateTime.Now;
                commentService.Add(comment);
                _Cache.Remove("Comment");
                _Cache.Add("Comment", JsonConvert.SerializeObject(commentService.GetModel(a => true).ToList()));
            }
            catch (Exception ex)
            {
            }
            return new JsonResult("");
        }
        /// <summary>
        /// 是否关闭评论
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        [Route("CheckComment")]
        public JsonResult CheckComment(int id)
        {
            bool result = false;
            List<Comment> comments = new List<Comment>();
            Article article = JsonConvert.DeserializeObject<List<Article>>(_Cache.Get("wz").ToString())
                .Where(a => a.Articleid == id).FirstOrDefault();
            if (article != null && article.CommentStatus.Contains("on"))
            {
                result = true;
            }
            return new JsonResult(result);
        }
        /// <summary>
        /// 评论列表
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <param name="order">排序:1-日期、other-投票数</param>
        /// <returns></returns>
        [Route("CommentList")]
        public JsonResult CommentList(int id, int order)
        {
            List<Comment> comments = new List<Comment>();
            List<UserInfo> userInfos = new List<UserInfo>();
            try
            {
                comments = JsonConvert.DeserializeObject<List<Comment>>(_Cache.Get("Comment").ToString())
                 .Where(a => a.Articleid == id).ToList();
                userInfos = JsonConvert.DeserializeObject<List<UserInfo>>(_Cache.Get("User").ToString());
                if (order == 1)
                {
                    var lists = comments.Join(userInfos, a => a.Userid, b => b.Userid, (a, b) => new { a, b })
                         .Select(a => new
                         {
                             Articleid = a.a.Articleid,
                             CommDate = a.a.CommDate,
                             Commentid = a.a.Commentid,
                             Content = a.a.Content,
                             Thumbs = a.a.Thumbs,
                             Userid = a.a.Userid,
                             Uname = a.b.Uname
                         }).OrderByDescending(a => a.CommDate).ToList();
                    return new JsonResult(new { list = lists, total = lists.Count });
                }
                else
                {
                    var lists = comments.Join(userInfos, a => a.Userid, b => b.Userid, (a, b) => new { a, b })
                        .Select(a => new
                        {
                            Articleid = a.a.Articleid,
                            CommDate = a.a.CommDate,
                            Commentid = a.a.Commentid,
                            Content = a.a.Content,
                            Thumbs = a.a.Thumbs,
                            Userid = a.a.Userid,
                            Uname = a.b.Uname
                        }).OrderByDescending(a => a.Thumbs).ToList();
                    return new JsonResult(new { list = lists, total = lists.Count });
                }
            }
            catch (Exception ex)
            {
                return new JsonResult("");
            }

        }
        /// <summary>
        /// 点赞数
        /// </summary>
        /// <param name="Commentid">评论编号</param>
        /// <param name="flag">true-点赞、false-取消</param>
        /// <returns></returns>
        [Route("Thumbs")]
        public string Thumbs(int Commentid, bool flag)
        {
            ICommentService commentService = Container.Resolve<ICommentService>();
            Comment comments = JsonConvert.DeserializeObject<List<Comment>>(_Cache.Get("Comment").ToString())
                .Where(a => a.Commentid == Commentid).FirstOrDefault();
            if (flag)
            {
                comments.Thumbs += 1;
            }
            else
            {
                comments.Thumbs -= 1;
            }
            commentService.Update(comments);
            _Cache.Remove("Comment");
            _Cache.Add("Comment", JsonConvert.SerializeObject(commentService.GetModel(a => true).ToList()));
            string num = comments.Thumbs.ToString();
            return num;
        }
        /// <summary>
        /// 用户名+编号
        /// </summary>
        /// <param name="result">评论功能是否开启</param>
        /// <returns></returns>
        [Authorize]
        [Route("CommentUser")]
        public JsonResult CommentUser(string token)
        {
            JwtSecurityToken strToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
            var list = strToken.Claims.ToList();
            Hashtable hashtable = new Hashtable();
            hashtable.Add("UserId", list[1].Value);
            hashtable.Add("UserName", list[0].Value);
            return new JsonResult(new { User = hashtable, result = true });
        }
        #endregion

        #region 关注
        /// <summary>
        ///  关注
        /// </summary>
        /// <param name="id">栏目编号</param>
        /// <param name="token">用户信息</param>
        /// <param name="isAttent">关注--取消关注</param>
        /// <returns></returns>
        [Authorize]
        [Route("Attent")]
        //[HttpPost]
        public JsonResult Attent(string id, string token, string isAttent)
        {
            IAttentService attentService = Container.Resolve<IAttentService>();
            bool flag = false;
            try
            {
                int no = int.Parse(id);
                int UserId = int.Parse(GetUser(token)["UserId"].ToString());
                Attent attent = new Attent() { CategoryId = no, Userid = UserId };
                if (isAttent == "1")
                {
                    attentService.Add(attent);
                    flag = true;
                }
                else
                {
                    attentService.Delete(attent);
                }
                return new JsonResult(flag);
            }
            catch (Exception ex)
            {
                return new JsonResult(ex.ToString());
            }

        }
        /// <summary>
        /// 关注状态
        /// </summary>
        /// <param name="CategoryId">栏目编号</param>
        /// <param name="token">用户</param>
        /// <returns></returns>
        [Authorize]
        [Route("CheckAttent")]
        public JsonResult CheckAttent(int CategoryId, string token)
        {
            bool flag = false;
            int UserId = int.Parse(GetUser(token)["UserId"].ToString());
            IAttentService attentService = Container.Resolve<IAttentService>();
            Attent attent = attentService.GetModel(a => a.Userid == UserId && a.CategoryId == CategoryId).FirstOrDefault();
            if (attent != null) flag = true;
            return new JsonResult(flag);
        }
        #endregion

        #endregion

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <returns></returns>
        public Hashtable GetUser(string token)
        {
            JwtSecurityToken strToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
            var list = strToken.Claims.ToList();
            Hashtable hashtable = new Hashtable();
            hashtable.Add("UserId", list[1].Value);
            hashtable.Add("UserName", list[0].Value);
            return hashtable;
        }
        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {

        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
